package com.epfresh.fragment;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.epfresh.R;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.OftenListActivity;
import com.epfresh.adapter.ViewBinderHomeOftenOffer;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.bean.AddCarResponse;
import com.epfresh.bean.CarCntResponse;
import com.epfresh.bean.HomeGoodsOften;
import com.epfresh.bean.ResultStringBean;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.CartHelper;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.FakeAddImageView;
import com.epfresh.views.PointFTypeEvaluator;
import com.epfresh.views.dialog.MsgDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import multitype.MultiTypeAdapter;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

/**
 * Author: Chen
 * Date: 2019/3/12
 * Desc:
 */
public class OftenListGoodsFrag extends BaseFragment {
    private RecyclerView rv_often_goods;
    private View rootView;
    private String categoryId;
    private int tabPos = -1;//标识当前fragment对应是哪个tab
    private int pageNum;

    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    private HomeGoodsOften homeGoodsOften;

    private CartHelper cartHelper = new CartHelper();
    private CarCntResponse carCntResponse;
    private View shoppingCartView;
    private ViewGroup mainLayout;
    private MsgDialog msgDialog;

    private boolean isVisibleToUser = false;//fragment是否可见
    private boolean isViewCreated = false;//View是否加载完成
    private boolean isFirstInit = false;

    @Override
    public String getBaseTag() {
        return "oftenListGoodsFrag";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.frag_often_list_goods, container, false);
            initView(rootView);
        }
        return rootView;
    }

    private void initIntent() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            categoryId = bundle.getString("categoryId");
            tabPos = bundle.getInt("tabPos");
        }
    }

    /**
     * 相关view的初始化
     *
     * @param rootView
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initView(View rootView) {
        rv_often_goods = rootView.findViewById(R.id.rv_often_goods);
        multiAdapter = new MultiTypeAdapter();

        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreViewBinder.setResourceId(R.layout.home_often_view_load_more);
        loadMoreDelegate.attach(rv_often_goods, loadMoreSubject);
        ViewBinderHomeOftenOffer viewBinderHomeOftenOffer = new ViewBinderHomeOftenOffer();
        viewBinderHomeOftenOffer.context = this;
        viewBinderHomeOftenOffer.setOnCartAddListener(new ViewBinderHomeOftenOffer.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, HomeGoodsOften.ContentBean goods, View v) {
                if (type == 1) {//购物车手动输入
                    openDialog(goods);
                } else if (type == 2) {//添加
                    MobclickAgent.onEvent(getAppActivity(), "Click_Home_OftenAddCart");
                    addCartCnt(v, goods, true);
                } else if (type == 3) {//减少
                    addCartCnt(v, goods, false);
                } else if (type == 5) {
                    if (goods.isDisabled())
                        return;
                    String id = goods.getId();
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    intent.putExtra("id", id + "");
                    intent.putExtra("storeId", goods.getStoreId());
                    intent.putExtra("promotionItemId", goods.getPromotionItemId());
                    intent.putExtra("serviceStoreId",goods.getServiceStoreId());
                    startActivity(intent);
                } else if (type == 0) {//删除商品
                    if (items.get(position) instanceof HomeGoodsOften.ContentBean) {
                        items.remove(position);
                        if (items.size() == 1 && items.get(0) instanceof LoadMoreItem) {
                            items.remove(0);
                        }
                        multiAdapter.notifyDataSetChanged();
                        requestDelete(goods);
                    }

                } else if (type == 10) {

                    if (goods.getShoppingCarId() == null) {
                        return;
                    }
                    requestFastMerTagList(goods);
                }
            }
        });
        multiAdapter.register(HomeGoodsOften.ContentBean.class, viewBinderHomeOftenOffer);
        multiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);

        multiAdapter.setItems(items);
        rv_often_goods.setLayoutManager(new LinearLayoutManager(getAppActivity()));
        rv_often_goods.setAdapter(multiAdapter);

//        rv_often_goods.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                LinearLayoutManager layoutManager = (LinearLayoutManager) rv_often_goods.getLayoutManager();
//                int firstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
//                if (firstCompletelyVisibleItemPosition != 0) {
//                    setNeedPass(true);
//                    Log.i("执行位置：", "firstCompletelyVisible");
//                }
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        setNeedPass(false);
//                        Log.i("执行位置：", "MotionEvent.ACTION_DOWN");
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        setNeedPass(false);
//                        Log.i("执行位置：", "MotionEvent.ACTION_MOVE");
//                        break;
//                }
//                return false;
//            }
//        });
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initCartView();
        isViewCreated = true;
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        lazyLoad();
    }

    private void lazyLoad() {
        if (!isVisibleToUser || !isViewCreated) {
            return;
        }
        loadGoods();
    }

    public void setFirstInit(boolean firstInit) {
        isFirstInit = firstInit;
    }

    /**
     * 加载商品
     */
    private void loadGoods() {
        if (!isFirstInit) {
            showProgressDialog();
        } else {
            isFirstInit = false;
        }
        pageNum = 0;
        items.clear();
        initIntent();
        reqOftenListGoods(categoryId);
    }

    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return true;
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            loadMoreGoods();
        }
    };

    /**
     * 加载更多商品
     */
    public void loadMoreGoods() {
        pageNum += 1;
        reqOftenListGoods(categoryId);
    }


    private void reqOftenListGoods(String categoryId) {
        if (TextUtils.isEmpty(categoryId)) {
            return;
        }
        Log.i("chen_categoryId", categoryId);
        Log.i("chen_tabPos",tabPos + "");
        RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(AppPurchaseRouterConstant.cmd_store_offen_oftenList);
        requestEntity.putParameter("topCategoryId", categoryId);
        requestEntity.putParameter("pageNumber", pageNum);
        requestEntity.putParameter("pageSize", "10");
        requestEntity.setCityId(ApplicationHelper.getInstance().getCity().getCityId());

        request(requestEntity, AppPurchaseRouterConstant.cmd_store_offen_oftenList, new OnRequestListener<HomeGoodsOften>() {
            @Override
            public HomeGoodsOften jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, HomeGoodsOften.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {
            }

            @Override
            public void onResponse(ResponseEntity<HomeGoodsOften> response, Object tag) {
                hideProgressDialog();
                homeGoodsOften = response.getResponseElement();

                List<HomeGoodsOften.ContentBean> list = new ArrayList<>();
                if (homeGoodsOften != null && homeGoodsOften.getContent() != null && homeGoodsOften.getContent().size() > 0) {
                    for (int i = 0; i < homeGoodsOften.getContent().size(); i++) {
                        if (i == 0 && pageNum == 0) {
                            homeGoodsOften.getContent().get(i).setNumOne(true);
                        } else {
                            homeGoodsOften.getContent().get(i).setNumOne(false);
                        }
                        if (i == homeGoodsOften.getContent().size() - 1) {
                            homeGoodsOften.getContent().get(i).setNumLast(true);
                        }else {
                            homeGoodsOften.getContent().get(i).setNumLast(false);
                        }
                    }

                    list.addAll(homeGoodsOften.getContent());

//                    if (homeGoodsOften.getShoppingCarCount() > 0) {
//                        showHomeOftenTitleRedTip(true);
//                    } else {
//                        showHomeOftenTitleRedTip(false);
//                    }
                }

                if (list.size() == 0) {
                    loadMoreDelegate.setStatusNoMore();
                } else {
                    loadMoreDelegate.addAllItem(items, list);
                }

                if (response.getResponseElement().isLast()) {
                    loadMoreDelegate.setStatusNoMore();
                } else {
                    loadMoreDelegate.setStatusNormal();
                }

                multiAdapter.notifyDataSetChanged();
            }
        });
    }

//    public void showHomeOftenTitleRedTip(boolean show) {
//        ((HomeActivity) getAppActivity()).homeFragment.setOftenTitleHasRedTip(show);
//    }

    public void requestCount() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt);
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        //首页已绑定用户，常购清单只看到散货；未绑定用户，只看到整货，且有比价问价 1整货 2散货
        int type;
        if (homeGoodsOften != null && homeGoodsOften.isAccountIsBindDc()) {
            type = 2;
        } else {
            type = 1;
        }
        re.putParameter("wholeSalesType", type);
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt, onCartCntRequestListener);
    }

    OnRequestListener<CarCntResponse> onCartCntRequestListener = new OnRequestListener<CarCntResponse>() {
        @Override
        public CarCntResponse jsonToObj(String s) {
            return new Gson().fromJson(s, CarCntResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<CarCntResponse> responseEntity, Object o) {
            carCntResponse = responseEntity.getResponseElement();
            if (carCntResponse != null) {
                carCntResponse.init();
            }
            updateCnt();
        }
    };


    public void openDialog(final HomeGoodsOften.ContentBean cartGood) {

        final Dialog dialog = new Dialog(getContext(), R.style.no_title_dialog);
        dialog.setContentView(R.layout.dialog_cart_add);

        ImageView ivAdd = dialog.findViewById(R.id.iv_add);
        ImageView ivRemove = dialog.findViewById(R.id.iv_remove);
        final EditText ed = dialog.findViewById(R.id.ed_price);

        ed.setText(FormatUtil.subZeroAndDot(cartGood.getCount() + ""));
        ed.setSelection(ed.length());
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 999999;
        ed.setFilters(new InputFilter[]{cashierInputFilter});
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;

//                if (FormatUtil.remainderZero(amount, cartGood.getInventory()) > 0) {
//                    amount = cartGood.getInventory();
//                }

                amount = FormatUtil.countAdd(amount, incr);
//                if (FormatUtil.remainderZero(amount, cartGood.getInventory()) > 0) {
//                    amount = cartGood.getInventory();
//                }

                cartGood.setShoppingCarProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        ivRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }

                amount = FormatUtil.countSubtract(amount, incr);
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }
                cartGood.setShoppingCarProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        dialog.findViewById(R.id.negativeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getAppActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.positiveButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double productCount = cartGood.getCount();
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }

                if (cnt < 0.01 || cnt < min) {
                    T.toast("不能少于" + FormatUtil.subZeroAndDot(min + ""));
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }

//                if (cnt > cartGood.getInventory()) {
//                    T.toast("超过库存");
//                    cnt = FormatUtil.countFormat(cartGood.getInventory(), incr, min);
//
//                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
//                    ed.setSelection(ed.getText().length());
//                    return;
//                }
                incr = incr < 0.01 ? min : incr;

                if (FormatUtil.isRemainder(cnt, incr, min)) {
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    Log.e("cnt:", "cnt:" + FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }

                reqCartCnt(cnt, cartGood);
                InputMethodManager imm = (InputMethodManager) getAppActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {

            }
        });

        dialog.show();
    }


    public void addCartCnt(View v, HomeGoodsOften.ContentBean goods, boolean isAdd) {
        double min = goods.getMoq();
        double incr = goods.getIncr();
        double amount = goods.getCount();


        if (isAdd) {
            amount = FormatUtil.countAdd(amount, incr);
        } else {
            amount = FormatUtil.countAdd(amount, -incr);
        }

//        if (FormatUtil.remainderZero(amount, goods.getInventory()) > 0) {
//            amount = goods.getInventory();
//            T.toast("库存不够");
//        } else {
//            if (isAdd)
//                addAnim(v);
//        }
        if (isAdd)
            addAnim(v);
        if (isAdd && FormatUtil.remainderZero(amount, goods.getMoq()) < 0) {
            amount = min;
        }


        if (!isAdd && (FormatUtil.remainderZero(amount, 0) <= 0 || FormatUtil.remainderZero(amount, min) < 0)) {
            amount = 0;
            reqCartCnt(amount, goods);
            return;
        }

        amount = FormatUtil.countFormat(amount, incr, min, goods.getInventory());
        reqCartCnt(amount, goods);

    }


    public void reqCartCnt(double productCount, HomeGoodsOften.ContentBean goods) {
        if (goods == null) {
            return;
        }
        goods.setShoppingCarProductCount(productCount);
        multiAdapter.notifyDataSetChanged();
        if (!cartHelper.checkIsCartRequesting(goods)) {
            updateCartCnt(productCount, goods);
        }
    }

    public void updateCartCnt(double productCount, HomeGoodsOften.ContentBean goods) {

        double count = goods.getShoppingCarProductCount();

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_add);
        re.putParameter("specId", goods.getId());
        re.putParameter("count", productCount);
        int serviceStoreId = goods.getServiceStoreId();
        if (serviceStoreId != -1) {
            re.putParameter("serviceStoreId", serviceStoreId);
        }
        RequestTag tag = new RequestTag();
        tag.tag = goods;
        tag.arg1 = productCount + "";
        tag.arg2 = count;
        if (cartHelper != null && goods != null) {
            cartHelper.updateRequest(goods.getUniqueKey());
        }
        request(re, tag, onCntRequestListener);
    }

    OnRequestListener<AddCarResponse> onCntRequestListener = new OnRequestListener<AddCarResponse>() {
        @Override
        public AddCarResponse jsonToObj(String s) {
            return new Gson().fromJson(s, AddCarResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof HomeGoodsOften.ContentBean) {
                    HomeGoodsOften.ContentBean goods = (HomeGoodsOften.ContentBean) o2;
                    if (arg2 != null && arg2 instanceof Double) {
                        responseCartCnt(true, goods, -1);
                        multiAdapter.notifyDataSetChanged();

                        T.toast(goods.getTitle() + " 添加购物车失败");
                    }
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (i / 10 == 40) {
                T.toast(o + "");
            }
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof HomeGoodsOften.ContentBean) {
                    HomeGoodsOften.ContentBean goods = (HomeGoodsOften.ContentBean) o2;
                    if (arg2 != null && arg2 instanceof Double) {
                        responseCartCnt(true, goods, -1);
                        multiAdapter.notifyDataSetChanged();

                        if (i / 100 != 4) {
                            T.toast(goods.getTitle() + " 添加购物车失败");
                        }
                    }
                }
            }
        }

        @Override
        public void onStart(Object o) {
        }

        @Override
        public void onResponse(ResponseEntity<AddCarResponse> responseEntity, Object o) {
            hideProgressDialog();
            AddCarResponse responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

                RequestTag tag;
                if (o instanceof RequestTag) {
                    tag = (RequestTag) o;
                    String arg1 = tag.arg1;
                    Object o2 = tag.tag;
                    if (arg1 != null && o2 != null && o2 instanceof HomeGoodsOften.ContentBean) {
                        HomeGoodsOften.ContentBean goods = (HomeGoodsOften.ContentBean) o2;
                        goods.setShoppingCarId(responseElement.getShoppingCarId());
                        DataManager.getInstance().updateCartCnt();
//                        if (responseElement.getshoppingCarCnt() == 0) {
//                            showHomeOftenTitleRedTip(false);
//                        } else {
//                            showHomeOftenTitleRedTip(true);
//                        }
                        responseCartCnt(false, goods, responseElement.getProductCnt());
                        if (carCntResponse == null) {
                            multiAdapter.notifyDataSetChanged();
                        } else {
                            carCntResponse.putCategoryCount(responseElement.getCategoryId(), responseElement.getCategoryCnt());
                            carCntResponse.putTopCategoryCount(responseElement.getTopCategoryId(), responseElement.getTopCategoryCnt());
                            carCntResponse.putPromotionCount(responseElement.getTopCategoryId(), responseElement.getPromotionCnt());
                            carCntResponse.putGoodsCount(goods.getIdPlus(), goods.getCount());
                            carCntResponse.putShopingCarId(goods.getIdPlus(), responseElement.getShoppingCarId());
                            if (responseElement.getProductCnt() == 0) {
                                carCntResponse.getMerMsgMap().remove(responseElement.getShoppingCarId());
                            }
                            updateCnt();
                        }
                    }
                }


            }
        }
    };

    public void responseCartCnt(boolean isFail, HomeGoodsOften.ContentBean goods, double cnt) {
        if (isFail) {
            cartHelper.responseCartFail(goods);
        } else {
            cartHelper.responseCartSuccess(goods, cnt);
        }
    }

    public void updateCnt() {

        if (carCntResponse != null) {

            if (items != null) {
                for (int i = 0; i < items.size(); i++) {
                    if (items.get(i) instanceof HomeGoodsOften.ContentBean) {
                        HomeGoodsOften.ContentBean item = (HomeGoodsOften.ContentBean) items.get(i);
                        if (cartHelper != null && cartHelper.isRequesting(item.getUniqueKey())) {
                            Log.e("continue", "cnt:down");
                            continue;
                        }
                        item.setShoppingCarProductCount(carCntResponse.getGoodsCount(item.getIdPlus()));
                        item.setShoppingCarId(carCntResponse.getShopingCarId(item.getIdPlus()));
                        if (carCntResponse != null && carCntResponse.getMerMsgMap() != null) {
                            item.setMsg(carCntResponse.getMerMsgMap().get(item.getShoppingCarId()));
                        }
                    }
                }
            }

            if (multiAdapter != null) {
                multiAdapter.notifyDataSetChanged();
            }
        }

    }


    public void requestDelete(HomeGoodsOften.ContentBean goods) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_often_delete);
        re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("productSpecId", goods.getId());
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_often_delete, onDeleteRequestListener);
    }

    OnRequestListener<ResultStringBean> onDeleteRequestListener = new OnRequestListener<ResultStringBean>() {
        @Override
        public ResultStringBean jsonToObj(String s) {
            return new Gson().fromJson(s, ResultStringBean.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<ResultStringBean> responseEntity, Object o) {
            if (items.size() == 0) {
                if (getAppActivity() instanceof OftenListActivity) {
                    ((OftenListActivity)getAppActivity()).removeOftenTab(tabPos);
                }
            }
        }
    };


    public void requestFastMerTagList(HomeGoodsOften.ContentBean cartGood) {

        if (cartGood == null) {
            return;
        }
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByProductId);
        re.putParameter("productId", cartGood.getId());

        RequestTag tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByProductId;
        tag.arg2 = cartGood;
        tag.type = RequestTag.TYPE_CURRENT;
        request(re, tag, onRequestFastMerTagListener);
    }

    OnRequestListener<List<String>> onRequestFastMerTagListener = new OnRequestListener<List<String>>() {
        @Override
        public List<String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof HomeGoodsOften.ContentBean) {

                    openMsgDialog((HomeGoodsOften.ContentBean) arg2, null);
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof HomeGoodsOften.ContentBean) {

                    openMsgDialog((HomeGoodsOften.ContentBean) arg2, null);
                }
            }

        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();


        }

        @Override
        public void onResponse(ResponseEntity<List<String>> responseEntity, Object o) {

            hideProgressDialog();
            List<String> responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.size() > 0) {

            }
            if (o != null && o instanceof RequestTag) {

                RequestTag tag = (RequestTag) o;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof HomeGoodsOften.ContentBean) {

                    openMsgDialog((HomeGoodsOften.ContentBean) arg2, responseElement);
                }
            }
        }
    };

    private void openMsgDialog(HomeGoodsOften.ContentBean goods, List<String> list) {
        msgDialog = new MsgDialog(getAppActivity());
        msgDialog.setOnCommitListener(new MsgDialog.OnCommitListener() {
            @Override
            public void onCommit(String msg, String goodsId) {
                msgDialog.dismiss();
                saveMsg(msg, goodsId);
            }
        });
        msgDialog.show(goods.getShoppingCarId(), list, goods.getMsg());
    }

    public void saveMsg(String msg, String goodsId) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg);
        re.putParameter("merMsg", msg);
        re.putParameter("shoppingCarId", goodsId);
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg, onSaveMsgRequestListener);
    }

    OnRequestListener<Map<String, Object>> onSaveMsgRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            T.toast(o + "");//arg + ",请点击重试"
        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {
            hideProgressDialog();
            if (msgDialog != null)
                msgDialog.dismiss();

            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean && ((Boolean) success)) {
                    requestCount();
                }
            }
        }
    };


    /**
     * 加购物车动画
     *
     * @param view
     */
    public void addAnim(View view) {
//        int[] addLocation = new int[2];
//        int[] cartLocation = new int[2];
//        view.getLocationInWindow(addLocation);
//        shoppingCartView.getLocationInWindow(cartLocation);
//
//        PointF startP = new PointF();
//        PointF endP = new PointF();
//        PointF controlP = new PointF();
//
//        startP.x = addLocation[0];
//        startP.y = addLocation[1];
//        endP.x = cartLocation[0] + LocalDisplay.dp2px(10);
//        endP.y = cartLocation[1] - getAppActivity().getResources().getDimensionPixelSize(R.dimen.bottom_nav_ic_height);
//        controlP.x = endP.x;
//        controlP.y = startP.y;
//        Log.e("location", "s===============");
//        Log.i("location", "sw:" + LocalDisplay.SCREEN_WIDTH_PIXELS);
//        Log.i("location", "sh:" + LocalDisplay.SCREEN_HEIGHT_PIXELS);
//        Log.i("location", "sx:" + startP.x);
//        Log.i("location", "sy:" + startP.y);
//        Log.i("location", "ex:" + endP.x);
//        Log.i("location", "ey:" + endP.y);
//        Log.e("location", "e===============");
//
//        final FakeAddImageView fakeAddImageView = new FakeAddImageView(getAppActivity());
//        mainLayout.addView(fakeAddImageView);
//        fakeAddImageView.setImageResource(R.drawable.cart_bezier);
//        fakeAddImageView.getLayoutParams().width = LocalDisplay.dp2px(10);
//        fakeAddImageView.getLayoutParams().height = LocalDisplay.dp2px(10);
//        fakeAddImageView.setVisibility(View.VISIBLE);
//        ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
//                new PointFTypeEvaluator(controlP), startP, endP);
//        addAnimator.setInterpolator(new AccelerateInterpolator());
//        addAnimator.addListener(new Animator.AnimatorListener() {
//            @Override
//            public void onAnimationStart(Animator animator) {
//                fakeAddImageView.setVisibility(View.VISIBLE);
//            }
//
//            @Override
//            public void onAnimationEnd(Animator animator) {
//                fakeAddImageView.setVisibility(View.GONE);
//                mainLayout.removeView(fakeAddImageView);
//            }
//
//            @Override
//            public void onAnimationCancel(Animator animator) {
//
//            }
//
//            @Override
//            public void onAnimationRepeat(Animator animator) {
//
//            }
//        });
        ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(shoppingCartView, "scaleX", 0.6f, 1.0f);
        ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(shoppingCartView, "scaleY", 0.6f, 1.0f);
        scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
        scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleAnimatorX).with(scaleAnimatorY);
        animatorSet.setDuration(340);
        animatorSet.start();

    }

    private void initCartView() {
        AppActivity appActivity = getAppActivity();
        if (appActivity instanceof OftenListActivity) {
            shoppingCartView = ((OftenListActivity) appActivity).getShoppingCartView();
//            mainLayout = ((HomeActivity) appActivity).getMainView();
        }
    }

    @Override
    public void onDestroyView() {
        if (rootView != null) {
            //Android不允许在容器中添加已有父容器的view
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
        isViewCreated = false;
        isVisibleToUser = false;
        super.onDestroyView();
    }

    /**
     * 设置外层RecyclerView拦截事件
     *
     * @param isNeedPass
     */
    private void setNeedPass(boolean isNeedPass) {
        ((HomeActivity) getAppActivity()).homeFragment.adjustPass(isNeedPass);
    }
}
